import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * @author krystal
 * @date 2022/12/8 18:42
 * 博客系统
 */
@WebServlet("/blog_delete")
public class BlogDeleteServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //1、先判定用户的登录状态
        HttpSession session = req.getSession(false);
        if (session == null) {
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您当前未登录，不能进行删除操作");
            return;
        }
        User user = (User) session.getAttribute("user");
        if (user == null) {
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您当前未登录，不能进行删除操作");
            return;
        }
        //2、获取到blogId
        String blogId=req.getParameter("blogId");
        if (blogId==null){
            //这个blogId参数不存在，无法删除
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您当前删除的blogId有误");
            return;
        }
        //3、查询出这个blogId对应的blog对象
        BlogDao blogDao=new BlogDao();
        Blog blog=blogDao.selectOne(Integer.parseInt(blogId));
        if (blog==null){
            resp.setStatus(404);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您当前删除的博客不存在，blogId="+blogId);
            return;
        }
        //4、判定登录用户是否就是文章作者
        if (blog.getUserId()!= user.getUserId()){
            //blog.getUserId()是文章作者id
            //user.getUserId()是session里登陆的用户
            resp.setStatus(403);
            resp.setContentType("text/html;charset=utf-8");
            resp.getWriter().write("您不能删除别人的博客");
            return;
        }
        //5、真正执行删除操作
        blogDao.delete(Integer.parseInt(blogId));
        //6、返回302重定向
        resp.sendRedirect("blog_list.html");
    }
}
